package cn.com.xy.sms.sdk.ui.menu;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import com.xy.smartsms.data.PublicInfoData;
import com.xy.smartsms.data.PublicInfoData.SubMenuItem;
import com.xy.smartsms.facade.SmsProcessFacade;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.ui.R;
import cn.com.xy.sms.sdk.ui.popu.util.ChannelContentUtil;
import cn.com.xy.sms.sdk.ui.popu.util.ContentUtil;
import cn.com.xy.sms.sdk.ui.popu.util.SmartSmsSdkUtil;
import cn.com.xy.sms.sdk.ui.popu.util.ViewUtil;
import cn.com.xy.sms.util.ParseManager;

public class PopMenusChanel extends PopMenus {
    private static final String TAG = "PopMenusChanel";

    private Object menuData;
    private Activity mContext;
    private PopupWindow mPopupWindow;
    private LinearLayout mListView;
    private View mContainerView;
    private View mParentView = null;
    private View mPopmenusArrow;
    private int mWidth;
    private int mHeight;
    private int mSimIndex = 0;
    private Map<String, String> mExtraMenuDataMap = null;

    private boolean mIsShow = false;

    public PopupWindow getmPopupWindow() {
        return mPopupWindow;
    }

    public View getmParentView() {
        return mParentView;
    }

    public boolean ismIsShow() {
        return mIsShow;
    }

    private String mPopCount = "-1";

    @SuppressLint("ResourceAsColor")
    public PopMenusChanel(Activity context, Object data, int width, int height) {
        mContext = context;
        menuData = data;
        mWidth = width;
        mHeight = height;

        mContainerView = LayoutInflater.from(context).inflate(R.layout.duoqu_popmenus, null);
        mListView = (LinearLayout) mContainerView.findViewById(R.id.layout_subcustommenu);
        mPopmenusArrow = mContainerView.findViewById(R.id.duoqu_popmenus_arrow);
        try {
            setSubMenu();
        } catch (Throwable e) {
            SmartSmsSdkUtil.smartSdkExceptionLog(TAG, e);
        }
        mListView.setFocusableInTouchMode(true);
        mListView.setFocusable(false);
        mPopupWindow = new PopupWindow(mContainerView, mWidth == 0 ? LayoutParams.WRAP_CONTENT : mWidth,
                mHeight == 0 ? LayoutParams.WRAP_CONTENT : mHeight);
        mPopupWindow.setAnimationStyle(R.style.popwin_anim_style);
    }

    public PopMenusChanel(Activity context, Object menuList, int width, int height, int simIndex,
                          Map<String, String> extraMenuDataMap) {
        this(context, menuList, width, height);
        mSimIndex = simIndex;
        mExtraMenuDataMap = extraMenuDataMap;
        mPopCount = mExtraMenuDataMap.get("popmenu_count");
    }

    public void showAtLocation(View parent) {
        mParentView = parent;
        showPopupAccordingParentView();
    }

    public void showPopupAccordingParentView() {
        if (mParentView == null) {
            return;
        }
        int pos = Integer.valueOf(mExtraMenuDataMap.get("popmenu_click_pos"));
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mContainerView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        int popupWith = mPopupWindow.getContentView().getMeasuredWidth();
        int parentWith = mParentView.getWidth();
        int x = 0;
        switch (pos) {
            case 0:
                if (mPopCount.equalsIgnoreCase("1") || mPopCount.equalsIgnoreCase("2")) {
                    mListView.setBackgroundResource(R.drawable.duoqu_menu);
                    x = parentWith / 2 - popupWith / 2;
                } else {
                    mListView.setBackgroundResource(R.drawable.duoqu_popup_left);
                    x = -ChannelContentUtil.DUOQU_MENU_ICON_WIDTH;
                }
                break;
            case 1:
                if (mPopCount.equalsIgnoreCase("2")) {
                    mListView.setBackgroundResource(R.drawable.duoqu_popup_right2);
                    x = -(popupWith - parentWith) + ViewUtil.dp2px(mContext, 13);
                } else {
                    mListView.setBackgroundResource(R.drawable.duoqu_menu);
                    x = -(parentWith / 2) - ContentUtil.DUOQU_MENU_BG_PADDING;
                }
                break;
            case 2:
                mListView.setBackgroundResource(R.drawable.duoqu_popup_right);
                x = -(mPopupWindow.getContentView().getMeasuredWidth() - mParentView.getWidth()) + ViewUtil.dp2px(mContext, 13);
                break;
        }

        mPopmenusArrow.setX(-x + parentWith / 2 - ChannelContentUtil.DUOQU_POPUPMENU_ARROW_WIDTH / 2);
        mPopupWindow.showAsDropDown(mParentView, x, -mPopupWindow.getContentView().getMeasuredHeight() - ViewUtil.dp2px(mContext, 25));
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(false);
        mPopupWindow.update();
        mPopupWindow.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                mIsShow = false;
                if (mParentView != null) {
                    ImageView imageView = (ImageView) mParentView.findViewById(R.id.douqu_menu_indicate);
                    imageView.setImageResource(R.drawable.duoqu_menu_arrow_down_icon);

                    mParentView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mParentView.setTag(null);
                        }
                    }, 200);
                }
                destory();
            }
        });
        mIsShow = true;
    }

    public void dismiss() {
        mPopupWindow.dismiss();
    }

    private void setSubMenu() {
        mListView.removeAllViews();
        JSONArray jsonArray = null;
        if (menuData instanceof JSONArray) {
            jsonArray = (JSONArray) menuData;
            setSubMenu(jsonArray);
        } else if (menuData instanceof List<?>) {
            try {
                setSubMenu((List<SubMenuItem>) menuData);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
    }

    private void setSubMenu(JSONArray jsonArray) {
        try {
            for (int i = 0; i < jsonArray.length(); i++) {
                final JSONObject ob = jsonArray.getJSONObject(i);
                boolean hasSp = true;
                if ((i + 1) == jsonArray.length()) {
                    hasSp = false;
                }
                LinearLayout layoutItem = setMenuItemStyle(hasSp, i + 1);
                setMenuData(layoutItem, ob);
                mListView.addView(layoutItem);
            }
            mListView.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void setSubMenu(List<PublicInfoData.SubMenuItem> menuList) throws JSONException {
        mListView.removeAllViews();
        int index = 0;
        for (final PublicInfoData.SubMenuItem menuItem : menuList) {
            // final JSONObject ob = mJsonArray.getJSONObject(i);
            boolean hasSp = true;
            if ((++index) == menuList.size()) {
                hasSp = false;
            }
            LinearLayout layoutItem = setMenuItemStyle(hasSp, index);
            layoutItem.setTag(index);
            setMenuData(layoutItem, menuItem);
            mListView.addView(layoutItem);
        }
        mListView.setVisibility(View.VISIBLE);
    }

    private void setMenuData(final LinearLayout layoutItem, final SubMenuItem menuItem) {
        TextView tv_funbtntitle = (TextView) layoutItem.findViewById(R.id.pop_item_textView);
        final String buttonName = menuItem.name;
        tv_funbtntitle.setText(buttonName);
        layoutItem.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    doNewAction(menuItem.json);
                    dismiss();
                } catch (Exception e) {
                    SmartSmsSdkUtil.smartSdkExceptionLog("setSubMenu() error: " + e.getMessage(), e);
                }
            }
        });

        layoutItem.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                try {
                    Integer clickTag = (Integer) layoutItem.getTag();
                    if (clickTag != null) {
                        if (clickTag != ((List<SubMenuItem>) menuData).size()) {
                            return false;
                        }
                    }
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            mPopmenusArrow.setBackgroundResource(R.drawable.duoqu_menu_arrow_clickble);
                            break;
                        case MotionEvent.ACTION_MOVE:
                            if(event.getX()<0 || event.getX() >layoutItem.getWidth() || event.getY() <0 || event.getY() > layoutItem.getY() ){
                                mPopmenusArrow.setBackgroundResource(R.drawable.duoqu_menu_arrow);
                                break;
                            }
                        default:
                    }
                } catch (Throwable ex) {
                    LogManager.e(TAG, ex.getMessage());
                }
                return false;
            }
        });
    }

    private void setMenuData(LinearLayout layoutItem, final JSONObject ob) {
        TextView tvFunbtntitle = (TextView) layoutItem.findViewById(R.id.pop_item_textView);

        try {
            tvFunbtntitle.setText(ob.getString("name"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        layoutItem.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try {
                    doAction(ob);
                    dismiss();
                } catch (Throwable e) {
                    SmartSmsSdkUtil.smartSdkExceptionLog(TAG, e);
                }

            }
        });
    }

    private LinearLayout setMenuItemStyle(boolean hasSpLine, int pos) {
        LinearLayout layoutItem = (LinearLayout) ((LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.duoqu_pomenu_menuitem, mListView, false);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT, 1.0f);
        mContainerView.setLayoutParams(lp);
        layoutItem.setFocusable(true);
        View popItemLine = layoutItem.findViewById(R.id.pop_item_line);
        if (!hasSpLine) {
            popItemLine.setVisibility(View.GONE);
            layoutItem.setBackgroundResource(R.drawable.duoqu_submenu_clickble_bottom);
        } else {
            if (pos <= 1) {
                layoutItem.setBackgroundResource(R.drawable.duoqu_submenu_clickble_top);
            } else {
                layoutItem.setBackgroundResource(R.drawable.duoqu_submenu_clickble_mid);
            }
        }
        return layoutItem;
    }

    protected void doAction(JSONObject ob) {
        Map<String, String> extend = new HashMap<String, String>();
        extend.put("simIndex", "0");
        try {
            ParseManager.doAction(mContext, ob.get("action_data").toString(), extend);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doNewAction(JSONObject menuItemData) {
        try {
            Map<String, String> extend = new HashMap<String, String>();
            extend.put("simIndex", String.valueOf(mSimIndex));
            extend.put("phoneNum", mExtraMenuDataMap.get("phoneNum"));
            extend.put("ManufactureData", menuItemData.optString("ManufactureData", "XIAOYUAN"));
            SmsProcessFacade.getInstance().processAction(mContext, menuItemData.toString(), extend);
        } catch (Throwable e) {
            SmartSmsSdkUtil.smartSdkExceptionLog("PopMenus doNewAction error: " + e.getMessage(), e);
        }
    }

    public void destory() {
        mContext = null;
        menuData = null;
    }

    public boolean isShow() {
        return mIsShow;
    }

    public static View bindMenuView(final View rootView, final PublicInfoData infoData, View.OnClickListener click,final Map<String,Object> extend) {
        if(rootView == null || infoData == null){
            return null;
        }
        final Context c = rootView.getContext();
        ViewGroup xyMenuContent = (ViewGroup) rootView.findViewById(R.id.layout_menu);
        View buttonToEditMenu = rootView.findViewById(R.id.layout_exchange);

        if(buttonToEditMenu != null && click != null){
            buttonToEditMenu.setOnClickListener(click);
        }
        LayoutInflater layoutInflater = (LayoutInflater) rootView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        xyMenuContent.removeAllViews();
        final int count = infoData.menuList.size();
        int index = 0;
        for (final PublicInfoData.MenuItem menuItem : infoData.menuList) {
            final int clickPos = index++;
            final LinearLayout layout = (LinearLayout) layoutInflater.inflate(R.layout.duoqu_item_custommenu, null);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    1.0f);
            layout.setLayoutParams(lp);
            TextView textViewName = (TextView) layout.findViewById(R.id.duoqu_custommenu_name);

            final ImageView imageViewIcon = (ImageView) layout.findViewById(R.id.douqu_menu_indicate);
            if (imageViewIcon != null   && menuItem.subMenuList != null && menuItem.subMenuList.size() > 0) {
                imageViewIcon.setVisibility(View.VISIBLE);
            }

            textViewName.setText(menuItem.name);
            layout.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Map<String, String> extendC = new HashMap<>();
                    if(extend != null){
                        String simIndex = String.valueOf(extend.get("simIndex"));
                        if(TextUtils.isEmpty(simIndex)){
                            simIndex = "-1";
                        }

                        extendC.put("simIndex", simIndex);
                        extendC.put("phoneNum", String.valueOf(extend.get("phoneNum")));
                        extendC.put("popmenu_count",  String.valueOf(count));
                        extendC.put("popmenu_click_pos",   String.valueOf(clickPos));
                    }

                    if (menuItem.subMenuList != null && menuItem.subMenuList.size() > 0) {
                        if (layout.getTag() != null) {
                            if(imageViewIcon != null){
                                imageViewIcon.setImageResource(R.drawable.duoqu_menu_arrow_down_icon);
                            }
                            return;
                        }

                        layout.setTag("FIRST");
                        if(imageViewIcon != null) {
                            imageViewIcon.setImageResource(R.drawable.duoqu_menu_arrow_up_icon);
                        }

                        PopMenus popMenu = new PopMenus((Activity)c,
                                menuItem.subMenuList,
                                0,
                                0,
                                -1,
                                extendC);
                        popMenu.showAtLocation(layout);
                    } else {
                        doNewAction(c,menuItem.json,extendC);
                    }
                }
            });
            xyMenuContent.addView(layout);
        }

        return xyMenuContent;
    }

    private static void doNewAction(Context context,JSONObject menuItemData,Map<String, String> extend) {
        HashMap<String, String> valueMap = new HashMap<String, String>();
        if (extend != null && !extend.isEmpty()) {
            for (Map.Entry<String, String> entry : extend.entrySet()) {
                    valueMap.put(entry.getKey(), (String) entry.getValue());
            }
        }
        try {
            valueMap.put("ManufactureData", menuItemData.optString("ManufactureData", "XIAOYUAN"));
            SmsProcessFacade.getInstance().processAction((Activity) context, menuItemData.toString(), valueMap);
        } catch (Throwable e) {
            e.printStackTrace();
            SmartSmsSdkUtil.smartSdkExceptionLog("PopMenus doNewAction error: " + e.getMessage(), e);
        }
    }
}
